package org.august.uid.transport;

import org.august.uid.kryo.KryoDecoder;
import org.august.uid.kryo.KryoEncoder;
import org.august.uid.msg.PackageMsg;
import org.august.uid.transport.handler.ClientHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;


public class NettyClient {

	// private static final Logger logger =
	// LoggerFactory.getLogger(NettyClient.class);

	private Channel channel;
	
	public void start() {
		
		Bootstrap clientBootstrap = new Bootstrap();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		
		try {
			clientBootstrap.group(workerGroup);
			clientBootstrap.channel(NioSocketChannel.class);
			clientBootstrap.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					System.out.println("==>>正在连接到服务端<<==");
					ChannelPipeline p = ch.pipeline();
					p.addLast(new KryoDecoder());
					p.addLast(new KryoEncoder());
					p.addLast(new ClientHandler());
				}
			});

			ChannelFuture channelFuture = clientBootstrap.connect("127.0.0.1", 8200).sync();
			if (channelFuture.isSuccess()) {
				System.out.println("===连接成功===");
				this.channel=channelFuture.channel();
			}
			channelFuture.channel().writeAndFlush(new PackageMsg());
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
			workerGroup.shutdownGracefully();
		}
		
		
		// channelFuture.channel().writeAndFlush(new PackageMsg());
	}
	
	public void sendMsg(PackageMsg packageMsg) {
		if(this.channel==null) {
			
		}
	}

	public static void main(String[] args) throws InterruptedException {
		NettyClient nettyClient = new NettyClient();
		nettyClient.start();
	}

}
